<template>
  <div class="bigBox">
    <div class="leftTable">
      <div class="form-containers">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="方案名称">
            <el-input v-model="formInline.user" placeholder="" @focus="clearableInput" clearable />
          </el-form-item>
          <el-form-item label="时间间隔">
            <el-select v-model="formInline.location" placeholder="" @change="selectData" clearable>
              <el-option label="15分钟" value="15分钟" />
              <el-option label="30分钟" value="30分钟" />
              <el-option label="1小时" value="1小时" />
              <el-option label="2小时" value="2小时" />
              <el-option label="3小时" value="3小时" />
              <el-option label="6小时" value="6小时" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="formInline.state" placeholder="" clearable style="width: 80px;">
              <el-option label="启用" value="启用" />
              <el-option label="停用" value="停用" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmitTablequery" size="small">查询</el-button>
            <el-button type="primary" size="small" @click="openDialog">新增</el-button>
            <el-button type="success" size="small" @click="dialogVisible1">编辑</el-button>
            <el-button type="danger" size="small" @click="DeletTable">删除</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="boxTable">
        <el-table class="boxTable1" :data="paginatedData" border style="height: 100%;" @row-click="handleCurrentChange"
          highlight-current-row>
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column v-for="(header, index) in headers" :key="index" :prop="header.prop" :label="header.label"
            :width="header.width" />
        </el-table>
      </div>
      <!-- <div v-if="tableData.length === 0">
        <el-empty description="暂无数据" />
      </div> -->
      <div v-if="tableData.length != 0" class="pagination-container"> <el-pagination background
          layout="total, sizes, prev, pager, next, jumper" :total="totalItems" :page-size="pageSize"
          :current-page="currentPage" @current-change="handlePageChange" @size-change="handlePageChange" /></div>
    </div>
    <div class="rightBox">
      <div class="form-container">
        <el-form :inline="true" :model="formInline">
          <el-form-item label="控制点名称">
            <el-input v-model="formInline.pointid" placeholder="" clearable />
          </el-form-item>
          <el-form-item label="日期">
            <el-date-picker  @clear="clearValue()"  v-model="formInline.date" type="daterange" range-separator="至" start-placeholder=""
              end-placeholder="" :size="size" @change="changeTime" style="width: 150px;" />
            <!-- <el-date-picker v-model="formInline.date" type="date" placeholder="" clearable style="width: 150px;" @change="changeTime"/> -->
            <el-button type="primary" @click="onSubmitRigth" size="small" style="margin-left: 10px;">查询</el-button>
            <el-button type="primary" size="small" @click="dyCpLimitTable">新增</el-button>
            <el-button type="success" @click="dialogedit2" size="small">编辑</el-button>
            <el-button type="danger" size="small" @click="DeletTable2">删除</el-button>
          </el-form-item>
          <!-- <el-form-item>
            <el-button type="primary" @click="onSubmit" size="small">查询</el-button>
          </el-form-item> -->

        </el-form>
      </div>
      <!-- 控制点名称管理表 -->
      <el-table  :row-class-name="tableRowClassName" :data="tableDatas" :span-method="objectSpanMethod" border
        style="width: 100%;overflow-y: scroll;height: 400px;" @row-click="handleRowClick" highlight-current-row>
        <!-- <el-table-column type="index" :index="indexMethod" /> -->
        <el-table-column v-for="(header, index) in header" :key="index" :prop="header.prop" :label="header.label"
          :width="header.width" />
      </el-table>
      <div class="rightEcharts">
        <ProgramEcharts></ProgramEcharts>
      </div>
    </div>
    <el-dialog v-model="dialogVisible" title="修改" width="550" draggable>
      <div style="display: flex;justify-content: space-between;">
        <div>
          <el-form-item label="方案名称" prop="name" label-width='75'>
            <el-input v-model="ruleForm.schemeName" />
          </el-form-item>
          <el-form-item label="试用部门" prop="name" label-width='75'>
            <el-input v-model="ruleForm.trialdepartment" />
          </el-form-item>
          <!-- <el-form-item label="统计频率" prop="name"
            <el-select v-model="formInline.resource" placeholder="15分钟" :disabled="!isSwitchOn" clearable>
              <el-option label="" value="" />
              <el-option label="" value="" />
            </el-select>
          </el-form-item> -->
          <el-form-item label="模式" prop="name" label-width='75'>
            <el-select v-model="ruleForm.schememode" placeholder="" clearable>
              <el-option label="天" value="天" />
              <el-option label="月" value="月" />
              <el-option label="季度" value="季度" />
              <el-option label="年" value="年" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="name" label-width='75'>
            <el-switch v-model="ruleForm.schemeState" @change="changeSeitch" />
          </el-form-item>
        </div>
        <div>
          <el-form-item label="方案编码" prop="name" label-width='75'>
            <el-input v-model="ruleForm.schemeCode" />
          </el-form-item>
          <el-form-item label="设置间隔" prop="name" label-width='75'>
            <el-select v-model="ruleForm.timeinterval" placeholder="" clearable @change="changeTime1">
              <el-option label="15分钟" value="15分钟" />
              <el-option label="30分钟" value="30分钟" />
              <el-option label="1小时" value="1小时" />
              <el-option label="2小时" value="2小时" />
              <el-option label="3小时" value="3小时" />
              <el-option label="6小时" value="6小时" />
            </el-select>
          </el-form-item>
          <el-form-item label="处置人" prop="name" label-width='75'>
            <el-input v-model="ruleForm.disposalpersonnel" />
          </el-form-item>

        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisibles">取消</el-button>
          <el-button type="primary" @click="dialogOverflowVisible1">
            保存
          </el-button>
        </div>
      </template>
      <div style="font-weight: 500;color: #000;">站点选择</div>
      <div style="margin-left: 65px;">
        <transfer></transfer>
      </div>
    </el-dialog>

    <el-dialog v-model="dialogOverflowVisible" title="修改" width="720" draggable overflow>
      <div style="display: flex;justify-content: space-between;">
        <div style="width: 280px;">
          <el-form-item label="站点名称" prop="name">
            <el-input v-model="ruleForm.name" />
          </el-form-item>
          <!-- <el-form-item label="传感器名称" prop="name">
            <el-input v-model="ruleForm.region" />
          </el-form-item> -->
          <el-form-item label="中心值" prop="name" style="width: 250px;margin-left: 30px;">
            <el-input v-model="ruleForm.center" />
          </el-form-item>
        </div>
        <div style="width: 280px;">
          <!-- <el-form-item label="传感器编码" prop="name">
            <el-input v-model="ruleForm.date2" />
          </el-form-item> -->
          <el-form-item label="浮动值" prop="name" style="width: 250px;margin-left: 30px;">
            <el-input v-model="ruleForm.floating" />
          </el-form-item>
          <el-form-item label="日期" prop="name" style="width: 235px;margin-left: 45px;">
            <el-date-picker v-model="ruleForm.dates" type="date" placeholder="" clearable  @change="dialogDeitTime"/>
          </el-form-item>
        </div>
      </div>
      <ProgramTable :formNumbers="{float:ruleForm.floating, center: ruleForm.center }" @save-edit="handlesSaveEdit" :diaolgTable="diaolgTable" style="height: 400px;"></ProgramTable>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogOverflowVisible = false">取消</el-button>
          <el-button type="primary" @click="preservationEdit">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
    <Dialog v-if="DialogIsg" @handleonSubmit="handleonSubmit" :DialogIsg="DialogIsg" @adialog="adialog" :tableID="tableID" :DataID="DataID"
      @onaddTable="onaddTable"></Dialog>
    <DyCpLimitDialog v-if="DialogIsgs" :DialogIsgs="DialogIsgs" @onSubmitRigth="onSubmitRigth" @dyCpLimitTable="dyCpLimitTable" ></DyCpLimitDialog>
  </div>
</template>

<script setup>
import { reactive } from 'vue'
import { ref, computed, onMounted } from 'vue';
import ProgramEcharts from '../../components/ProgramEcharts.vue'
import ProgramTable from '../../components/ProgramTable.vue'
import transfer from '../../components/transfer.vue'
import bus from '../../tools/eventBus'
import { postupdateAllManage,postprojectManageOrder, postupdateSiteLimit, postgetSiteLimit, puteditTable2, PlanTableList, DyCpLimit, DyprojectManageID, DyprojectManageEdit, DyTableQuery, DyTableDelete, postaddSiteupdate, putpointEdit, putdelettable2 } from '../../../src/http/http'
import Dialog from '../../components/Dialog.vue'
import DyCpLimitDialog from '../../components/DyCpLimitDialog.vue'
import { ElMessage } from 'element-plus'
import { dataValue } from '../../tools/ProgramManage'
import { dataValue1 } from '../../tools/pointid'
import { dataValue2 } from '../../tools/pointids'
const isFirstTime = ref(true); // 父组件的 isFirstTime 状态
const ruleForm = reactive({
  schemeName: '',//控制点名称
  schemeCode: '',//方案名称
  schemeState: false,//状态
  schemeStates: '',//状态
  schememode: '',//控制点编码
  trialdepartment: '',//试用部门
  timeinterval: '',//时间间隔
  disposalpersonnel: '',//处置人
  // trialdepartment: '',//试用部门
  pointid: '',
  date: '',
  dates: '',
  date2: '',
  delivery: true,
  location: '',
  type: [],
  resource: '',
  desc: '',
  pattern: '',
  floating: '',
  center: '',
  personnel: ''
})

const currentPage = ref(1);
const pageSize = ref(20);
const dialogVisible = ref(false)
const dialogOverflowVisible = ref(false)
// const isSwitchOn = ref(true)
const DialogIsg = ref(false)
const DialogIsgs = ref(false)
const echartsData = ref([])
const tableData = ref([])
const tableDatas = ref([])
const tableID = ref(null)
const startTime = ref(null)
const endTime = ref(null)
const DataID = ref(null)
const tableID2 = ref(null)
const pointid1 = ref(null)
const schemaid1 = ref(null)
const schemaid = ref(null)
const programTableData = ref(null);
const onetabledata = ref({})
const formInline = reactive({
  user: '',
  region: '',
  date: '',
  state: '',
  location: '',
  pointid: '',
})
const siteIddelete = ref([])
const siteModify = ref ([])
const sitename = ref ([])
const allIds = ref ([])
const chinaTime = ref ('')
function handleonSubmit(){
  console.log('刷新了');
  onSubmitTablequery()
}


//接收方案编辑所需数据
bus.on('schemEditdate', (data) => {
  siteIddelete.value = [],
  siteModify.value  = [],
  sitename.value = []
console.log('需要删除：', data.originSites,'需要修改：',data.checkedSites,'名称：',data.sitename);
siteIddelete.value = data.originSites //需要删除的
siteModify.value = data.checkedSites //需要修改
sitename.value = data.sitename //需要删除的
})

//新增事件
const diaolgTable = ref('')
const threename = ref('')
function onaddTable() {
  console.log('触发了');
  onSubmitRigth()
}
function tableRowClassName({ row, rowIndex }) {
      // 条件判断：如果是第一行，添加 `my-custom-class`
      if (rowIndex === 0) {
        return 'my-custom-class';
      }
      // 你可以根据其他条件添加不同的类名
      return '';
    }
  


const handlesSaveEdit = (tableData) => {
  console.log(tableData,'pp');
  programTableData.value = tableData
}

function dialogDeitTime(time){
// console.log(time,'time');
const date = new Date(time);
const options = { timeZone: "Asia/Shanghai", year: "numeric", month: "2-digit", day: "2-digit" };
  const formattedDate = date.toLocaleDateString("zh-CN", options).replace(/\//g, '-');
  chinaTime.value = formattedDate;
console.log(chinaTime.value);

}
//清空时间

//控制点限制管理删除

function DeletTable2() {
// 找出 schemaid 为 48b5c2f1-5a94-418d-9581-6cea060c3093 的所有 id
 const result = tableDatas.value.filter(item => item.schemaid === schemaid1.value).map(item => item.id);

  // console.log(res);
  
console.log(tableDatas.value,tableID2.value,result);

result.forEach((res)=>{
  putdelettable2(res).then(()=>{
    console.log(res);
})
})

  // if(res.state === 200){
  tableData2()
  // }
}

function dialogedit2() {
  diaolgTable.value = '编辑'
  if (tableID2.value != null) {
    dialogOverflowVisible.value = true
  } else {
    ElMessage({
      message: '请先选择编辑数据',
      type: 'warning',
    });
  }
  puteditTable2(tableID2.value).then((res) => {
    console.log(res.data.returnValue.limitday);
    ruleForm.name = res.data.returnValue.sitename
    ruleForm.center = res.data.returnValue.limitmedian
    ruleForm.floating = res.data.returnValue.limitfloat
    ruleForm.dates = res.data.returnValue.limitday
  })

  //编辑列表回显

  postgetSiteLimit({ "schemeID": schemaid1.value, 'pointID': pointid1.value }).then((res) => {
    console.log(res.data, '编辑列表回显');
    if(res.status === 200){
      onSubmitRigth()
    }
    bus.emit('eidtData', {
      revriced: res.data,
    })
  })
}

function preservationEdit() {  
  dialogOverflowVisible.value = false
  //编辑
  putpointEdit({
    "dataChange": [
      {
        "ChangeType": "Modify",
        "ChangeInfo": {
          "DataId": tableID2.value,
          "sitename": ruleForm.name,
          // 'limitmedian':ruleForm.center,
          // 'limitfloat':ruleForm.floating,
          //  'dateTimes':chinaTime.value,

        }
      }
    ],
    "variableChange": null
  }).then((res) => {
    console.log(res);

  })
  const newData = programTableData.value.reduce((acc, item) => {
    // 创建 lowlimit 对象
    const lowlimitItem = {
      timeperiod: item.timeperiod,
      limitmedian: Number(ruleForm.center),
      limitfloat:Number(ruleForm.floating),
      dateTimes: chinaTime.value ,
      lowlimit: item.lowlimit,
      remark: 'low',
      monitorName: formInline.schemeName
    };

    // 创建 highlimit 对象
    const highlimitItem = {
      timeperiod: item.timeperiod,
      limitmedian: Number(ruleForm.center),
      limitfloat: Number(ruleForm.floating),
      dateTimes: chinaTime.value ,
      highlimit: item.highlimit,
      remark: 'high',
      monitorName: formInline.schemeName
    };

    // 把这两条数据加入结果数组
    acc.push(lowlimitItem, highlimitItem);

    return acc;
  }, []);

  console.log(newData);

  postupdateSiteLimit(newData).then((res) => {
   if(res.status === 200){
    onSubmitRigth()
    onSubmitTablequery()
   }
  })
}

function changeTime1(e) {
  console.log(e, '时间选择');
  // 转换为本地时间
}

//左右表格联查

function abc2() {
  let data3 = [
    { name1: schemaid.value },
    { name2: startTime.value },
    { name3: endTime.value },
  ]

  // console.log(dataValue1(data3));

  return {
    "entityFilter": {
      "FilterConditions": dataValue2(data3),
      "SortConditions": [],
      "IsUsePagination": true,
      "Pagination": {
        "PageIndex": 1,
        "PageSize": 20,
        "PageCount": 0,
        "TotalCount": 0
      }
    },
    "requestInfo": {
      "dataChange": [],
      "variableChange": null
    }
  }

}

//方案管理联查

function onSubmitRigth1() {
  DyCpLimit(abc2()).then((res) => {
    console.log(res.data.returnValue.result);
    res.data.returnValue.result.sort((a, b) => a.schemaid.localeCompare(b.schemaid));

// 按 schemaid 分
const groupedData =  res.data.returnValue.result.reduce((acc, item) => {
  if (!acc[item.schemaid]) {
    acc[item.schemaid] = [];
  }
  acc[item.schemaid].push(item);
  return acc;
}, {});

// 对每个 schemaid 组中的数据进行交替排序
const result = Object.values(groupedData).flatMap(group => {
  const highLimit = group.filter(item => item.limitstate === '高限');
  const lowLimit = group.filter(item => item.limitstate === '低限');
  
  const sortedGroup = [];
  const maxLength = Math.max(highLimit.length, lowLimit.length);
  
  for (let i = 0; i < maxLength; i++) {
    if (i < highLimit.length) sortedGroup.push(highLimit[i]);
    if (i < lowLimit.length) sortedGroup.push(lowLimit[i]);
  }
  
  return sortedGroup;
});
tableDatas.value = result

console.log(result);


    // console.log(tableDatas.value,'000');
    handleRowClick(tableDatas.value[0])
     allIds.value = tableDatas.value.map(item => item.id);
  })
}

function handleCurrentChange  (currentRow) {
  localStorage.setItem('siteId', currentRow.id);
  // schemaids.value = currentRow.id;
  console.log('当前选中行:', currentRow);
  schemaid.value = currentRow.id; // 更新 schemaid
 
  onSubmitRigth1();
  // 获取所有行元素
  const tableRows = document.querySelectorAll('.el-table__row');

  // 移除之前的高亮
  tableRows.forEach((row) => {
    row.style.backgroundColor = ''; // 清除高亮颜色
  });

  // 获取当前选中行的索引
  const rowIndex = tableData.value.indexOf(currentRow);

  // 设置当前选中行的高亮
  const selectedRow = tableRows[rowIndex];
  if (selectedRow) {
    selectedRow.style.backgroundColor = '#ecf5ff'; // 为选中行设置高亮颜色
  }
};


//清空表单
const dialogVisibles = () => {
  dialogVisible.value = false
  if (!formEl) return
  formEl.resetFields()
}

function openDialog() {
  threename.value = '新增'
  DialogIsg.value = !DialogIsg.value,
  // Dyexpressionss()
  bus.emit('threename', { threename:'新增'})
  
}

// function Dyexpressionss(){
//   Dyexpressions(1726021337397).then((res)=>{

//   })
// }


function dyCpLimitTable() {
  DialogIsgs.value = !DialogIsgs.value
  diaolgTable.value = '新增'
}

function DeletTable() {
  onetabledata.value = null
  DyTableDelete(schemaid.value).then((res) => {
    if (res.status === 200) {
      onSubmitTablequery()
      console.log('修改成功');
      // ElMessage({
      //   message: '删除成功',
      //   type: 'success',
      // })
      // 页面刷新
    }
  })

console.log(allIds.value);


allIds.value.forEach((item)=>{
  putdelettable2(item).then(()=>{
 
})
})
onSubmitRigth()

}

//时间间隔

function selectData(e) {
  console.log(e);
  formInline.location = e
}

function Tablequery() {
  console.log(formInline.location);
  let data4 = [
    { name1: formInline.user },
    { name2: formInline.state },
    { name3: formInline.location }
  ]

  console.log(dataValue(data4), ' dataValue(data4)');

  return {
    "entityFilter": {
      "FilterConditions": dataValue(data4),
      "SortConditions": [],
      "IsUsePagination": true,
      "Pagination": {
        "PageIndex": 1,
        "PageSize": 20,
        "PageCount": 0,
        "TotalCount": 0
      }
    },
    "requestInfo": {
      "dataChange": [],
      "variableChange": null
    }
  }

}

// function onSubmitTablequery1(){
//   console.log('lll');

// }

//排序查询
// function handleorderTable() {
//   // postprojectManageOrder().then((res) => {
//   //   console.log(res);
//   //   console.log('排序');
//   //   tableData.value = res.data
//   // })
// }


function onSubmitTablequery() {
  if(formInline.user== '' &&  formInline.location == '' && formInline.state == ''){
    postprojectManageOrder().then((res) => {
    console.log(res);
    console.log('排序');
    tableData.value = res.data
  })
  console.log('为空');
  
  }else{
    console.log('查询');
  DyTableQuery(Tablequery()).then((res) => {
      tableData.value =  res.data.returnValue.result;
  })

  }
 
}
function dialogData() {
  return {
    "dataChange": [
      {
        "ChangeType": "Modify",
        "ChangeInfo": {
          "DataId": schemaid.value,
          "schemeName": ruleForm.schemeName,
          "schemeCode": ruleForm.schemeCode,
          "schememode": ruleForm.schememode,
          "timeintervals": ruleForm.timeinterval,
          "schemeStates": ruleForm.schemeStates,
          "disposalpersonnel": ruleForm.disposalpersonnel,
          'trialdepartment': ruleForm.trialdepartment,
          "schemeorder": ruleForm.delivery
        }
      }
    ],
    "variableChange": null
  }
}


function dialogOverflowVisible1() {

  dialogVisible.value = false
  // console.log(datas,'datas');
  DyprojectManageEdit(dialogData()).then((res) => {
    if (res.status === 200) {
      console.log('修改成功');
      ElMessage({
        message: '修改成功',
        type: 'success',
      })
      // 页面刷新
    }
  })

 postupdateAllManage({schemeID: schemaid.value,
                      siteIds:siteModify.value,
                      sitename:sitename.value,
                      siteIdDelete:siteIddelete.value}).then((res)=>{
    console.log(res.data,'方案编辑');

    if (res.status === 200) {
      window.location.reload();
    }
    
  })
  onSubmitTablequery()
  onSubmitRigth()

}


// const openDialog = (event) => {
//   DialogIsg.value = !DialogIsg.value 

//   const buttonText = (event.target).innerText;
//   console.log(buttonText);
// }

function dialogVisible1() {
  // isFirstTime.value = true; // 设置为 false，当点击编辑时更新子组件的状态
  // bus.emit('threename', { threename:'编辑'})
      localStorage.setItem('threeType', isFirstTime.value);
      
  onetabledata.value = null
  if (schemaid.value != null) {
    dialogVisible.value = true;
  } else {
    ElMessage({
      message: '请先选择编辑数据',
      type: 'warning',
    });
  }

  if (!formInline.state) {
    ruleForm.schemeState = '停用';
  } else {
    formInline.state = '启用';
  }

  DyprojectManageID(schemaid.value)
    .then((res) => {
      // console.log(res.data, '控制点');
      ruleForm.schemeName = res.data.returnValue.schemeName;
      ruleForm.schemeCode = res.data.returnValue.schemeCode;
      ruleForm.schemeState = res.data.returnValue.schemeStates;
      ruleForm.schememode = res.data.returnValue.schememode;
      ruleForm.trialdepartment = res.data.returnValue.trialdepartment; // 部门
      ruleForm.timeinterval = res.data.returnValue.timeintervals;
      ruleForm.disposalpersonnel = res.data.returnValue.disposalpersonnel;

      if (res.data.returnValue.schemeStates === '启用') {
        ruleForm.schemeState = true;
      } else {
        ruleForm.schemeState = false;
      }

      console.log(ruleForm.timeinterval);

    })
    .catch((error) => {
      console.error('DyprojectManageID 错误:', error);
    });

  postaddSiteupdate({ id:schemaid.value })
    .then((res) => {
      console.log(res.data);
      const idArray = res.data.flat().map(item => item.id);

      // 打印结果数组
      console.log(idArray,'树列表回显'); // 
      bus.emit('checkBox', {
        revriced: idArray,
        three:isFirstTime.value,
      })
    })
    .catch((error) => {
      console.error('postaddSiteupdate 错误:', error);
    });
}



function adialog(value) {
  DialogIsg.value = value
}

function changeSeitch(e) {
  // console.log(e, 'e');
  if (!e) {
    ruleForm.schemeStates = '停用'

  } else {
    ruleForm.schemeStates = '启用'

  }
}
const indexMethod = (index) => {
  return index * 1;
}
// 自定义单元格合并逻辑
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  // 对前两列进行操作
  if (columnIndex === 0 || columnIndex === 0 || columnIndex === 0) {
    if (rowIndex % 2 === 0) {
      return {
        rowspan: 2, // 合并两行
        colspan: 1,
      };
    } else {
      return {
        rowspan: 0, // 跳过当前行
        colspan: 0,
      };
    }
  }
};

// 处理行点击事件
const handleRowClick = (row) => {
  echartsData.value = []
  console.log('点击的行数据：', row)
  tableID2.value = row.id
  schemaid1.value = row.schemaid
  pointid1.value = row.pointid
  // console.log('点击的行数据：', row.id)
  
  const tableRow = document.querySelectorAll('.my-custom-class')
  tableRow.forEach((row)=>{
    row.style.backgroundColor = ''
  })
  console.log(row,tableDatas.value);
  
  const rowIndexs = tableDatas.value.indexOf(row)

  const selectedRows = tableRow[rowIndexs]
  if(selectedRows){
    selectedRows.style.backgroundColor = '#ecf5ff'
  }
  // console.log(echartsData.value);
  postgetSiteLimit({"schemeID": row.schemaid, 'pointID': row.pointid }).then((res)=>{
    console.log(res.data,'ercharts数据');
    echartsData.value = res.data
    bus.emit('echartsSoure', {
    echartsData: echartsData.value,
    echartsName:row.sitename,
  })
  })

  // monitorhistory().then((res)=>{
  //   console.log(res);
    
  // })
}

function clearableInput() {
  console.log('获取焦点');
  // formInline.user = ''
  // formInline.location = ''
  // formInline.region = ''
}
// 处理行点击事件
const handleRowClick1 = (row, column, event) => {
  tableID.value = row.id

}

function PlanTable() {
  const params = {
    "entityFilter": {
      "FilterConditions": [],
      "SortConditions": [],
      "IsUsePagination": true,
      "Pagination": {
        "PageIndex": 1,
        // "PageSize": ,
        "PageCount": 0,
        "TotalCount": 0
      }
    },
    "requestInfo": {
      "dataChange": [],
      "variableChange": null
    }
  };

  PlanTableList(params).then((res) => {
    console.log(res.data.returnValue.result, 'fangan');
    tableData.value = res.data.returnValue.result
  });

}

onMounted(() => {
  PlanTable()
  tableData2()
  setTimeout(() => {
    if (tableData.value.length > 0) {
      handleCurrentChange(tableData.value[0]); // 选中第一行
    }


  }, 100)


});


function tableData2() {
  const param = {
    "entityFilter": {
      "FilterConditions": [],
      "SortConditions": [],
      "IsUsePagination": true,
      "Pagination": {
        "PageIndex": 1,
        "PageSize": 20,
        "PageCount": 0,
        "TotalCount": 0
      }
    },
    "requestInfo": {
      "dataChange": [],
      "variableChange": null
    }
  }

  DyCpLimit(param).then((res) => {
    console.log(res.data.returnValue.result, '控制点');
    tableDatas.value = res.data.returnValue.result
  });


  if (tableDatas.value.length > 1) {
    handleRowClick(tableDatas.value[0], null, null);
    handleRowClick(tableDatas.value[1], null, null);
  }

}

const onSubmit = () => {
  console.log('submit!')
}

// 定义表头数据
const headers = ref([
  { prop: 'schemeName', label: '方案名称', width: 150 },
  { prop: 'schemeCode', label: '方案编码', width: 100 },
  { prop: 'schememode', label: '模式', width: 100 },
  { prop: 'timeintervals', label: '时间间隔', width: 100 },
  { prop: 'trialdepartment', label: '试用部门', width: 100 },
  { prop: 'disposalpersonnel', label: '处置人', width: 100 },
  { prop: 'schemeStates', label: '状态', width: 100 },
  // { prop: 'schemeorder', label: '排序', width: 100 },
  { prop: 'remark', label: '备注', width: 100 },
])

const header = ref([
  { prop: 'sitename', label: '站点名称', width: 150 },
  // { prop: 'schemaid', label: '站点id', width: 150 },
  // { prop: 'pointid', label: '控制点id', width: 150 },
  { prop: 'limitstate', label: '类型', width: 100 },
  // { prop: 'schemaid', label: '方案id', width: 100 },
  { prop: 'limithour1', label: '01:00', width: 80 },
  { prop: 'limithour2', label: '02:00', width: 80 },
  { prop: 'limithour3', label: '03:00', width: 80 },
  { prop: 'limithour4', label: '04:00', width: 80 },
  { prop: 'limithour5', label: '05:00', width: 80 },
  { prop: 'limithour6', label: '06:00', width: 80 },
  { prop: 'limithour7', label: '07:00', width: 80 },
  { prop: 'limithour8', label: '08:00', width: 80 },
  { prop: 'limithour9', label: '09:00', width: 80 },
  { prop: 'limithour10', label: '10:00', width: 80 },
  { prop: 'limithour11', label: '11:00', width: 80 },
  { prop: 'limithour12', label: '12:00', width: 80 },
  { prop: 'limithour13', label: '13:00', width: 80 },
  { prop: 'limithour14', label: '14:00', width: 80 },
  { prop: 'limithour15', label: '15:00', width: 80 },
  { prop: 'limithour16', label: '16:00', width: 80 },
  { prop: 'limithour17', label: '17:00', width: 80 },
  { prop: 'limithour18', label: '18:00', width: 80 },
  { prop: 'limithour19', label: '19:00', width: 80 },
  { prop: 'limithour20', label: '20:00', width: 80 },
  { prop: 'limithour21', label: '21:00', width: 80 },
  { prop: 'limithour22', label: '22:00', width: 80 },
  { prop: 'limithour23', label: '23:00', width: 80 },
  { prop: 'limithour24', label: '00:00', width: 80 },
  { prop: 'limitmedian', label: '中心值', width: 80 },
  { prop: 'limitfloat', label: '浮动值', width: 80 },

])
const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = currentPage.value * pageSize.value;
  return tableData.value.slice(start, end);
});



// 总条目数
const totalItems = computed(() => tableData.value.length);

// 处理页码变化
const handlePageChange = (page) => {
  currentPage.value = page;
};


//控制点查询

//时间选择
function changeTime(e) {
  // console.log(e, '时间选择');
  // 转换为本地时间
  if(e != null){
    const TimeValue = e.map(timeString => {
    const date = new Date(timeString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，+1调整为1-12
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`; // 格式化为 YYYY-MM-DD
  })

  console.log(TimeValue, 'TimeValue')
  startTime.value = TimeValue[0]
  endTime.value = TimeValue[1]
  }

}


function abc() {
  let data3 = [
    { name1: formInline.pointid },
    { name2: startTime.value },
    { name3: endTime.value },
  ]

  console.log(dataValue1(data3));

  return {
    "entityFilter": {
      "FilterConditions": dataValue1(data3),
      "SortConditions": [],
      "IsUsePagination": true,
      "Pagination": {
        "PageIndex": 1,
        "PageSize": 20,
        "PageCount": 0,
        "TotalCount": 0
      }
    },
    "requestInfo": {
      "dataChange": [],
      "variableChange": null
    }
  }

}
function onSubmitRigth() {
  DyCpLimit(abc()).then((res) => {
    console.log(res.data.returnValue.result);
//     res.data.returnValue.result.sort((a, b) => {
//     if (a.schemaid < b.schemaid) return -1;
//     if (a.schemaid > b.schemaid) return 1;
//     return 0;
// });
// res.data.returnValue.result.sort((a, b) => a.schemaid.localeCompare(b.schemaid));

// 按 schemaid 排序
res.data.returnValue.result.sort((a, b) => a.schemaid.localeCompare(b.schemaid));

// 按 schemaid 分
const groupedData =  res.data.returnValue.result.reduce((acc, item) => {
  if (!acc[item.schemaid]) {
    acc[item.schemaid] = [];
  }
  acc[item.schemaid].push(item);
  return acc;
}, {});

// 对每个 schemaid 组中的数据进行交替排序
const result = Object.values(groupedData).flatMap(group => {
  const highLimit = group.filter(item => item.limitstate === '高限');
  const lowLimit = group.filter(item => item.limitstate === '低限');
  
  const sortedGroup = [];
  const maxLength = Math.max(highLimit.length, lowLimit.length);
  
  for (let i = 0; i < maxLength; i++) {
    if (i < highLimit.length) sortedGroup.push(highLimit[i]);
    if (i < lowLimit.length) sortedGroup.push(lowLimit[i]);
  }
  
  return sortedGroup;
});

console.log(result);

// console.log(res.data.returnValue.result);
    // tableDatas.value = res.data.returnValue.result
    tableDatas.value =result
  })
}

function clearValue() {
    // console.log('11');
    startTime.value = ''
    endTime.value = ''
}

</script>

<style scoped>


.cell-content {
  width: 100px;
  /* 固定单元格宽度 */
  height: 40px;
  /* 固定单元格高度 */
  overflow: hidden;
  /* 隐藏超出内容 */
  text-overflow: ellipsis;
  /* 超出内容用省略号显示 */
  white-space: nowrap;
  /* 防止文本换行 */
  display: flex;
  align-items: center;
  /* 垂直居中 */
  justify-content: center;
  /* 水平居中 */
}

.bigBox {
  /* width: 100%; */
  height: 100vh;
  display: flex;
  justify-content: space-around;
  /* border: solid 1px red; */
  /* padding: 0; */
  /* background-color: #fff; */
  padding-left: 70px;
}

.rightBox {
  width: 49.5%;
  height: 100vh;
  display: grid;
}


.rightEcharts {
  background-color: #fff;

}

.leftTable {
  width: 49.5%;
}

.demo-form-inline .el-input {
  --el-input-width: 140px;
}

.demo-form-inline .el-select {
  --el-select-width: 140px;
}

.form-container {
  /* display: flex; */
  /* justify-content: center; */
  margin-top: 10px;
  margin-left: 20px;
  /* height: 100vh; 使容器高度占满整个视口 */
}

.form-containers {
  display: flex;
  justify-content: space-around;
  margin-top: 10px;
  /* height: 100vh; 使容器高度占满整个视口 */
}


.rightTableBox {
  overflow-x: scroll;
  width: 50%;

}

.boxTable1 {
  position: relative;
}

.pagination-container {
  /* position: absolute; */
  position: fixed;
  right: 50%;
  bottom: 0;
  z-index: 999;
}

::v-deep .el-table--enable-row-transition .el-table__body td.el-table__cell {
  height: 40px !important;
  /* transition: background-color .25s ease; */
}
</style>